//
//  WBOAuthViewController.swift
//  CustomWeiBo
//
//  Created by laiqiang on 21/5/17.
//  Copyright © 2021年 laiqiang. All rights reserved.
//

import UIKit
import SVProgressHUD

//微博 授权 网页
class WBOAuthViewController: UIViewController {

    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        title = "登录新浪微博"
        view.backgroundColor = UIColor.white
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", targe: self, action: #selector(backMain))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", targe: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBredirect_uri)"
        //https://api.weibo.com/oauth2/authorize?client_id=1620610038&redirect_uri=https://www.sina.com
        //https://api.weibo.com/oauth2/authorize?client_id=1620610038&response_type=code&redirect_uri=https://weibo.com
        //错误码:21322 重定向地址不匹配   处理：微博开放平台－我的应用－高级信息－OAuth2.0 授权设置 回调页面
        guard let url = URL(string: urlString)
            else {
            return
        }
        
        let urlRequest = URLRequest.init(url: url)
        webView.loadRequest(urlRequest)
        webView.scalesPageToFit = true
        webView.scrollView.isScrollEnabled = false
        webView.delegate = self
//        webView.scrollView.addObserver(self, forKeyPath: "contentsize", options: [.new], context: nil)
        
        /**
         1.获取授权
         client_id 申请应用时分配的AppKey ：1620610038
         redirect_uri 授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。baidu.com,一般用新浪的网址
         授权参数 oauth2/authorize
         请求授权URL https://api.weibo.com/oauth2/authorize
         请求授权拼接到完整的URL
         请求授权URL https://api.weibo.com/oauth2/authorize?client_id=1620610038&redirect_uri=baidu.com
         */
    }
    
    @objc fileprivate func backMain() {
        
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    func autoFill() {
       
        //密码自动填充===webview 注入(修改本地缓存的页面)
        //点击登录 －执行submit（）将本地数据提交到服务器
        let js = "document.getElementById(userId).value = 185xxxxxx6" + "document.getElementById(passwd).value = wbxxxxxxx"
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
    
    
//    deinit {
//        webView.scrollView.removeObserver(self, forKeyPath: "contentsize")
//    }
    
//    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//        
//        if keyPath == "contentSize" {
//            
//            let actualSize = webView.sizeThatFits(CGSize.zero)
//            let newFrame = CGRect(x: webView.frame.origin.x, y: webView.frame.origin.y, width: actualSize.width, height: actualSize.height)
//            webView.frame = newFrame;
//        }
//    }
}

extension WBOAuthViewController : UIWebViewDelegate {
    /// webView 将要加载请求
    ///
    ///   - webView: webView
    ///   - request: 将要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("微博请求－－－－－\(request.url?.absoluteString)")
        
        guard let absoluteString = request.url?.absoluteString else {
            return true//不存在url 加载 错误webview自己处理
        }
        
        if (absoluteString.hasPrefix(WBredirect_uri) == false) {
            return true //存在url 不存在“需要的值”，webview加载错误页面，https://weibo.com
        }
        
        //query 就是？后面的值
        print("微博请求－－－－－\(request.url?.query)")
        guard let query = request.url?.query else {
            return true//不存在数据 加载 错误webview自己处理
        }
        
        if query.hasPrefix("code=") == false {
            
            print("取消授权－－－－")
            backMain()
            return false
        }
        
        let code = query.substring(from: "code=".endIndex) 
        print("微博请求code= －－－－－\(code)")
        
        WBNetworkingManager.share.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败！")
            }
            else{
                SVProgressHUD.showInfo(withStatus: "登录成功！")
                //发送通知，弹出授权的页面的控制器，刷新页面
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),
                    object: nil)
                self.backMain()
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
